﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Collections.Concurrent;
using System.Collections;

namespace LogLib
{
    /// <summary>
    /// 专用于写日记的线程
    /// </summary>
    public class Writer
    {         
        public Writer()
        {
          
        }

        private static object lockState = new object();
   
        /// <summary>
        /// 将一行信息写入日记文件
        /// </summary>
        /// <param name="fullFilePath">日记文件路径</param>
        /// <param name="line">一行日记信息</param>
        public void WriteLine(LogInfo info)
        {
            lock (lockState)
            {
                using (FileStream fs = new FileStream(info.LogFullName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (StreamWriter streamWriter = new StreamWriter(fs))
                    {
                        streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                        if (!string.IsNullOrEmpty(info.Content))
                        {
                            streamWriter.WriteLine(info.Content);
                        }
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                    fs.Close();
                }
            }          
        }

        /// <summary>
        /// 将多行信息写入日记文件
        /// </summary>
        /// <param name="fullFilePath">日记文件路径</param>
        /// <param name="strContentLine">一行日记信息</param>
        public void WriteLines(LogInfoList infos)
        {
            lock (lockState)
            {
                try
                {
                    using (FileStream fs = new FileStream(infos.LogFullName, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter(fs))
                        {
                            streamWriter.BaseStream.Seek(0, SeekOrigin.End);
                            foreach (string line in infos.ListLines)
                            {
                                if (!string.IsNullOrEmpty(line))
                                {
                                    streamWriter.WriteLine(line);
                                }
                            }
                            streamWriter.Flush();
                            streamWriter.Close();
                        }
                        fs.Close();
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteExceptionAsync(ex.ToString());
                }              
            }
        }
    }

}
